// 全局变量
let cartItems = [];
let isLoggedIn = false;
let currentUser = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有功能
    initBannerSlider();
    initSearch();
    initModals();
    initCart();
    initProductCards();
    initSmoothScroll();
    initLazyLoading();
    
    // 检查登录状态
    checkLoginStatus();
});

// 轮播图功能
function initBannerSlider() {
    const dots = document.querySelectorAll('.dot');
    const slides = document.querySelectorAll('.slide');
    let currentSlide = 0;
    
    if (dots.length === 0 || slides.length === 0) return;
    
    // 点击圆点切换轮播图
    dots.forEach((dot, index) => {
        dot.addEventListener('click', () => {
            showSlide(index);
        });
    });
    
    // 显示指定幻灯片
    function showSlide(index) {
        // 移除所有活动状态
        slides.forEach(slide => slide.classList.remove('active'));
        dots.forEach(dot => dot.classList.remove('active'));
        
        // 设置当前幻灯片为活动状态
        slides[index].classList.add('active');
        dots[index].classList.add('active');
        
        currentSlide = index;
    }
    
    // 自动轮播
    if (slides.length > 1) {
        setInterval(() => {
            currentSlide = (currentSlide + 1) % slides.length;
            showSlide(currentSlide);
        }, 5000);
    }
}

// 搜索功能
function initSearch() {
    const searchInput = document.querySelector('.search-box input');
    const searchButton = document.querySelector('.search-box button');
    const searchSuggestions = document.getElementById('searchSuggestions');
    
    if (!searchInput || !searchButton) return;
    
    // 搜索按钮点击事件
    searchButton.addEventListener('click', performSearch);
    
    // 回车键搜索
    searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            performSearch();
        }
    });
    
    // 输入时显示建议
    searchInput.addEventListener('input', debounce(() => {
        const query = searchInput.value.trim();
        if (query.length > 0) {
            showSearchSuggestions(query);
        } else {
            hideSearchSuggestions();
        }
    }, 300));
    
    // 点击建议项
    if (searchSuggestions) {
        searchSuggestions.addEventListener('click', (e) => {
            if (e.target.closest('.suggestion-item')) {
                const suggestion = e.target.closest('.suggestion-item').querySelector('span').textContent;
                searchInput.value = suggestion;
                performSearch();
                hideSearchSuggestions();
            }
        });
    }
    
    // 点击外部隐藏建议
    document.addEventListener('click', (e) => {
        if (!e.target.closest('.search-box') && !e.target.closest('.search-suggestions')) {
            hideSearchSuggestions();
        }
    });
    
    function performSearch() {
        const query = searchInput.value.trim();
        if (query) {
            showNotification(`搜索: ${query}`, 'info');
            console.log('搜索关键词:', query);
            hideSearchSuggestions();
        }
    }
    
    function showSearchSuggestions(query) {
        if (searchSuggestions) {
            searchSuggestions.style.display = 'block';
        }
    }
    
    function hideSearchSuggestions() {
        if (searchSuggestions) {
            searchSuggestions.style.display = 'none';
        }
    }
}

// 模态框管理
function initModals() {
    const modals = document.querySelectorAll('.modal');
    const closeButtons = document.querySelectorAll('.close');
    
    // 关闭按钮事件
    closeButtons.forEach(button => {
        button.addEventListener('click', () => {
            const modal = button.closest('.modal');
            closeModal(modal);
        });
    });
    
    // 点击模态框外部关闭
    modals.forEach(modal => {
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                closeModal(modal);
            }
        });
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            const openModal = document.querySelector('.modal[style*="display: block"]');
            if (openModal) {
                closeModal(openModal);
            }
        }
    });
    
    // 登录按钮事件
    const loginButton = document.querySelector('.login');
    if (loginButton) {
        loginButton.addEventListener('click', (e) => {
            e.preventDefault();
            openModal('loginModal');
        });
    }
    
    // 注册按钮事件
    const registerButton = document.querySelector('.register');
    if (registerButton) {
        registerButton.addEventListener('click', (e) => {
            e.preventDefault();
            openModal('registerModal');
        });
    }
    
    // 购物车按钮事件
    const cartButton = document.querySelector('.cart');
    if (cartButton) {
        cartButton.addEventListener('click', (e) => {
            e.preventDefault();
            openModal('cartModal');
            updateCartDisplay();
        });
    }
    
    // 模态框切换
    const showRegisterLink = document.getElementById('showRegister');
    const showLoginLink = document.getElementById('showLogin');
    
    if (showRegisterLink) {
        showRegisterLink.addEventListener('click', (e) => {
            e.preventDefault();
            closeModal('loginModal');
            openModal('registerModal');
        });
    }
    
    if (showLoginLink) {
        showLoginLink.addEventListener('click', (e) => {
            e.preventDefault();
            closeModal('registerModal');
            openModal('loginModal');
        });
    }
    
    // 表单提交事件
    initAuthForms();
}

// 打开模态框
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';
    }
}

// 关闭模态框
function closeModal(modal) {
    if (typeof modal === 'string') {
        modal = document.getElementById(modal);
    }
    if (modal) {
        modal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }
}

// 认证表单初始化
function initAuthForms() {
    const loginForm = document.getElementById('loginForm');
    const registerForm = document.getElementById('registerForm');
    const sendCodeButton = document.getElementById('sendCode');
    
    // 登录表单
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
    }
    
    // 注册表单
    if (registerForm) {
        registerForm.addEventListener('submit', handleRegister);
    }
    
    // 发送验证码
    if (sendCodeButton) {
        sendCodeButton.addEventListener('click', sendVerificationCode);
    }
}

// 处理登录
function handleLogin(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    const email = formData.get('email');
    const password = formData.get('password');
    const remember = formData.get('remember');
    
    // 简单的表单验证
    if (!email || !password) {
        showNotification('请填写完整的登录信息', 'error');
        return;
    }
    
    // 模拟登录请求
    showLoading(e.target.querySelector('button[type="submit"]'));
    
    setTimeout(() => {
        hideLoading(e.target.querySelector('button[type="submit"]'));
        
        // 模拟登录成功
        if (email === 'test@example.com' && password === '123456') {
            isLoggedIn = true;
            currentUser = { email, name: '测试用户' };
            localStorage.setItem('user', JSON.stringify(currentUser));
            localStorage.setItem('remember', remember ? 'true' : 'false');
            
            showNotification('登录成功！', 'success');
            closeModal('loginModal');
            updateUserInterface();
        } else {
            showNotification('邮箱或密码错误', 'error');
        }
    }, 1000);
}

// 处理注册
function handleRegister(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    const phone = formData.get('phone');
    const email = formData.get('email');
    const password = formData.get('password');
    const confirmPassword = formData.get('confirmPassword');
    const code = formData.get('code');
    const agree = formData.get('agree');
    
    // 表单验证
    if (!phone || !email || !password || !confirmPassword || !code) {
        showNotification('请填写完整的注册信息', 'error');
        return;
    }
    
    if (password !== confirmPassword) {
        showNotification('两次输入的密码不一致', 'error');
        return;
    }
    
    if (!agree) {
        showNotification('请同意用户协议和隐私政策', 'error');
        return;
    }
    
    // 模拟注册请求
    showLoading(e.target.querySelector('button[type="submit"]'));
    
    setTimeout(() => {
        hideLoading(e.target.querySelector('button[type="submit"]'));
        showNotification('注册成功！请登录', 'success');
        closeModal('registerModal');
        openModal('loginModal');
    }, 1000);
}

// 发送验证码
function sendVerificationCode() {
    const button = document.getElementById('sendCode');
    const phoneInput = document.getElementById('registerPhone');
    
    if (!phoneInput.value.trim()) {
        showNotification('请先输入手机号', 'warning');
        return;
    }
    
    // 模拟发送验证码
    button.disabled = true;
    let countdown = 60;
    
    const timer = setInterval(() => {
        button.textContent = `${countdown}秒后重发`;
        countdown--;
        
        if (countdown < 0) {
            clearInterval(timer);
            button.disabled = false;
            button.textContent = '发送验证码';
        }
    }, 1000);
    
    showNotification('验证码已发送', 'info');
}

// 购物车功能
function initCart() {
    // 添加购物车按钮点击事件
    document.addEventListener('click', (e) => {
        if (e.target.classList.contains('btn-buy')) {
            e.preventDefault();
            addToCart(e.target);
        }
    });
    
    // 结算按钮
    const checkoutBtn = document.getElementById('checkoutBtn');
    if (checkoutBtn) {
        checkoutBtn.addEventListener('click', handleCheckout);
    }
}

// 添加到购物车
function addToCart(button) {
    const productCard = button.closest('.product-card');
    if (!productCard) return;
    
    const productName = productCard.querySelector('h3')?.textContent || '未知商品';
    const productPrice = productCard.querySelector('.product-price')?.textContent || '¥0';
    const productImage = productCard.querySelector('img')?.src || '';
    
    // 检查商品是否已在购物车中
    const existingItem = cartItems.find(item => item.name === productName);
    
    if (existingItem) {
        existingItem.quantity += 1;
    } else {
        cartItems.push({
            id: Date.now(),
            name: productName,
            price: productPrice,
            image: productImage,
            quantity: 1
        });
    }
    
    updateCartBadge();
    showNotification(`${productName} 已添加到购物车`, 'success');
    
    // 保存到本地存储
    localStorage.setItem('cartItems', JSON.stringify(cartItems));
}

// 更新购物车徽章
function updateCartBadge() {
    const cartButton = document.querySelector('.cart');
    const totalItems = cartItems.reduce((sum, item) => sum + item.quantity, 0);
    
    // 移除现有的徽章
    const existingBadge = cartButton.querySelector('.cart-badge');
    if (existingBadge) {
        existingBadge.remove();
    }
    
    // 添加新徽章
    if (totalItems > 0) {
        const badge = document.createElement('span');
        badge.className = 'cart-badge';
        badge.textContent = totalItems > 99 ? '99+' : totalItems;
        cartButton.appendChild(badge);
    }
}

// 更新购物车显示
function updateCartDisplay() {
    const cartEmpty = document.getElementById('cartEmpty');
    const cartItems = document.getElementById('cartItems');
    const cartItemList = document.getElementById('cartItemList');
    const totalPriceElement = document.querySelector('.total-price');
    
    if (cartItems.length === 0) {
        cartEmpty.style.display = 'block';
        cartItems.style.display = 'none';
    } else {
        cartEmpty.style.display = 'none';
        cartItems.style.display = 'block';
        
        // 渲染购物车商品
        cartItemList.innerHTML = '';
        let totalPrice = 0;
        
        cartItems.forEach(item => {
            const price = parseFloat(item.price.replace('¥', '').replace(',', ''));
            const itemTotal = price * item.quantity;
            totalPrice += itemTotal;
            
            const cartItem = document.createElement('div');
            cartItem.className = 'cart-item';
            cartItem.innerHTML = `
                <img src="${item.image}" alt="${item.name}" class="cart-item-image">
                <div class="cart-item-info">
                    <div class="cart-item-name">${item.name}</div>
                    <div class="cart-item-price">${item.price}</div>
                    <div class="cart-item-quantity">
                        <button class="quantity-btn" onclick="updateQuantity(${item.id}, -1)">-</button>
                        <input type="number" class="quantity-input" value="${item.quantity}" 
                               onchange="updateQuantity(${item.id}, this.value - ${item.quantity})">
                        <button class="quantity-btn" onclick="updateQuantity(${item.id}, 1)">+</button>
                        <span class="cart-item-remove" onclick="removeFromCart(${item.id})">
                            <i class="fas fa-trash"></i>
                        </span>
                    </div>
                </div>
            `;
            cartItemList.appendChild(cartItem);
        });
        
        if (totalPriceElement) {
            totalPriceElement.textContent = `¥${totalPrice.toFixed(2)}`;
        }
    }
}

// 更新商品数量
function updateQuantity(itemId, change) {
    const item = cartItems.find(item => item.id === itemId);
    if (item) {
        const newQuantity = item.quantity + change;
        if (newQuantity > 0) {
            item.quantity = newQuantity;
        } else {
            removeFromCart(itemId);
            return;
        }
        
        updateCartBadge();
        updateCartDisplay();
        localStorage.setItem('cartItems', JSON.stringify(cartItems));
    }
}

// 从购物车移除
function removeFromCart(itemId) {
    cartItems = cartItems.filter(item => item.id !== itemId);
    updateCartBadge();
    updateCartDisplay();
    localStorage.setItem('cartItems', JSON.stringify(cartItems));
    showNotification('商品已从购物车移除', 'info');
}

// 处理结算
function handleCheckout() {
    if (!isLoggedIn) {
        showNotification('请先登录', 'warning');
        closeModal('cartModal');
        openModal('loginModal');
        return;
    }
    
    if (cartItems.length === 0) {
        showNotification('购物车为空', 'warning');
        return;
    }
    
    showNotification('正在跳转到支付页面...', 'info');
    setTimeout(() => {
        showNotification('支付功能开发中', 'info');
    }, 1000);
}

// 检查登录状态
function checkLoginStatus() {
    const savedUser = localStorage.getItem('user');
    const remember = localStorage.getItem('remember');
    
    if (savedUser && remember === 'true') {
        currentUser = JSON.parse(savedUser);
        isLoggedIn = true;
        updateUserInterface();
    }
    
    // 恢复购物车数据
    const savedCart = localStorage.getItem('cartItems');
    if (savedCart) {
        cartItems = JSON.parse(savedCart);
        updateCartBadge();
    }
}

// 更新用户界面
function updateUserInterface() {
    const loginButton = document.querySelector('.login');
    const registerButton = document.querySelector('.register');
    
    if (isLoggedIn && currentUser) {
        if (loginButton) {
            loginButton.textContent = currentUser.name;
            loginButton.href = '#';
            loginButton.onclick = (e) => {
                e.preventDefault();
                showUserMenu();
            };
        }
        if (registerButton) {
            registerButton.style.display = 'none';
        }
    } else {
        if (loginButton) {
            loginButton.textContent = '登录';
            loginButton.onclick = (e) => {
                e.preventDefault();
                openModal('loginModal');
            };
        }
        if (registerButton) {
            registerButton.style.display = 'inline-block';
        }
    }
}

// 显示用户菜单
function showUserMenu() {
    const menu = document.createElement('div');
    menu.className = 'user-menu';
    menu.innerHTML = `
        <div class="user-menu-item" onclick="showUserProfile()">个人中心</div>
        <div class="user-menu-item" onclick="showOrders()">我的订单</div>
        <div class="user-menu-item" onclick="logout()">退出登录</div>
    `;
    
    // 移除现有菜单
    const existingMenu = document.querySelector('.user-menu');
    if (existingMenu) {
        existingMenu.remove();
    }
    
    // 添加新菜单
    const loginButton = document.querySelector('.login');
    if (loginButton) {
        loginButton.parentNode.appendChild(menu);
    }
}

// 退出登录
function logout() {
    isLoggedIn = false;
    currentUser = null;
    localStorage.removeItem('user');
    localStorage.removeItem('remember');
    
    showNotification('已退出登录', 'info');
    updateUserInterface();
    
    // 移除用户菜单
    const userMenu = document.querySelector('.user-menu');
    if (userMenu) {
        userMenu.remove();
    }
}

// 产品卡片交互
function initProductCards() {
    document.addEventListener('click', (e) => {
        if (e.target.closest('.product-card')) {
            const productCard = e.target.closest('.product-card');
            const productName = productCard.querySelector('h3')?.textContent || '未知商品';
            showProductDetail(productName);
        }
    });
}

// 显示产品详情
function showProductDetail(productName) {
    showNotification(`查看 ${productName} 详情`, 'info');
    // 这里可以跳转到产品详情页或显示详情模态框
}

// 平滑滚动
function initSmoothScroll() {
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });
}

// 显示通知
function showNotification(message, type = 'success') {
    // 移除现有通知
    const existingNotifications = document.querySelectorAll('.notification');
    existingNotifications.forEach(notification => {
        notification.remove();
    });
    
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    // 自动移除通知
    setTimeout(() => {
        notification.style.opacity = '0';
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
}

// 懒加载
function initLazyLoading() {
    const images = document.querySelectorAll('img[data-src]');
    
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.removeAttribute('data-src');
                observer.unobserve(img);
            }
        });
    });
    
    images.forEach(img => imageObserver.observe(img));
}

// 显示加载状态
function showLoading(element) {
    if (element) {
        const originalText = element.textContent;
        element.disabled = true;
        element.innerHTML = '<span class="loading"></span> 处理中...';
        element.dataset.originalText = originalText;
    }
}

// 隐藏加载状态
function hideLoading(element) {
    if (element && element.dataset.originalText) {
        element.disabled = false;
        element.textContent = element.dataset.originalText;
        delete element.dataset.originalText;
    }
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 导出工具函数到全局
window.MiMall = {
    showNotification,
    debounce,
    throttle,
    showLoading,
    hideLoading
}; 